package com.ywt.cda.action;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ywt.cda.access.Access;
import com.ywt.cda.action.model.ConsmersModel;
import com.ywt.cda.action.vo.AgeCompareVo;
import com.ywt.cda.domain.AnaImportData;
import com.ywt.cda.domain.enums.DimensionFlag;
import com.ywt.cda.domain.enums.SexEnum;
import com.ywt.cda.enums.FunctionsEnum;
import com.ywt.cda.service.ConsumersService;
import com.ywt.cda.service.GoodsService;
import com.ywt.cda.service.ParamValidateService;
import com.ywt.cda.utils.DateUtils;
import com.ywt.cda.utils.NumberUtil;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;

/**
 * （消费者分析）
 * <br>（功能详细描述）
 *
 * @author lougf
 * @version V1.0
 * @see [相关类/方法]
 * @since 2016年3月31日 上午10:06:08
 */
@Controller
public class ConsumersAction {

    private Logger logger = Logger.getLogger(ConsumersAction.class);

    @Resource
    private ParamValidateService paramValidateService;
    @Resource
    private ConsumersService consumersService;
    @Resource
    private GoodsService goodsService;
    

    /**
     * 
     * getImportArea(进口消费者群体分析 )
     * <br>(这里描述这个方法适用条件 – 可选)
     * @param model
     * @return 
     * @exception 
     * @since 2016年3月22日 上午10:41:13
     * @author lougf
     */
    @RequestMapping("import/consumers")
    @Access(FunctionsEnum.IMPORT_CUNSUMERS)
    public String getImportConsumers(
            @ModelAttribute("consmersModel") ConsmersModel consmersModel,
            Model model) {
        if (null == consmersModel) {

            // 默认查近七天
            consmersModel = new ConsmersModel();
            Date date = new Date();
            String today = DateUtils.format(date, "yyyy-MM-dd");
            consmersModel.setStartTime(DateUtils.getSpecifiedDayBefore(
                    today, 6));
            consmersModel.setEndTime(today);
            model.addAttribute("default", true);
        }
        if (null != consmersModel) {
            if (StringUtils.isBlank(consmersModel.getStartTime())
                    && StringUtils.isBlank(consmersModel.getEndTime())) {
                // 默认查近七天

                Date date = new Date();
                String today = DateUtils.format(date, "yyyy-MM-dd");
                consmersModel.setStartTime(DateUtils.getSpecifiedDayBefore(
                        today, 6));
                consmersModel.setEndTime(today);
                model.addAttribute("default", true);
            }
        }

        // 第一步：校验输入参数
        if (!paramValidateService.validate(consmersModel)) {
            logger.info("error param!");
            model.addAttribute("error", "error param!");
            return "error";
        }

        Date starttime = DateUtils.getDate(consmersModel.getStartTime(), "yyyy-MM-dd");
        Date endtime = DateUtils.getDate(consmersModel.getEndTime(), "yyyy-MM-dd");
        Integer days =  DateUtils.daysBetween(starttime,endtime);
        if(days > 150){
            consmersModel.setStartTime_F(DateUtils.format(starttime,"yyyy-MM"));
            consmersModel.setEndTime_F(DateUtils.format(endtime,"yyyy-MM"));
            consmersModel.setStartTimePattern("yyyy-MM");
        }

        // 查询品类排名
        List<AnaImportData> datas4 =  consumersService.getImortDataByCategory(consmersModel);
        goodsService.initImportDataMainName(datas4, DimensionFlag.S_CATEGORY);
        //计算客单价(总金额除以总数量)
        model.addAttribute("avgprice", "0");
        model.addAttribute("datas4", datas4);
        if(null != datas4 && datas4.size() > 0) {
            BigDecimal allSumNum = new BigDecimal(new Double("0"));
            BigDecimal allSumPrice = new BigDecimal(new Double("0"));
            for (AnaImportData data : datas4) {
                if (null != data.getSumPrice()) {
                    allSumPrice = allSumPrice.add(data.getSumPrice());
                }
                if (null != data.getSumNum()) {
                    allSumNum = allSumNum.add(data.getSumNum());
                }
            }
            model.addAttribute("avgprice", String.valueOf(NumberUtil.div(allSumPrice.doubleValue(),allSumNum.doubleValue(),2)));
        }
        //计算 男女比例
        List<AnaImportData> datas5 =  consumersService.getImortDataBySex(consmersModel);
        model.addAttribute("womanscale", "0");
        model.addAttribute("manscale", "0");
        if(null != datas5 && datas5.size() > 0){
            BigDecimal allCountNum = new BigDecimal(new Double("0"));
            BigDecimal allSumNum = new BigDecimal(new Double("0"));
            BigDecimal manCountNum =  new BigDecimal(new Double("0"));
            BigDecimal womanCountNum =  new BigDecimal(new Double("0"));
            for(AnaImportData data : datas5){
                if(null != data.getMainCodeCount()){
                    allCountNum = allCountNum.add(data.getMainCodeCount()) ;
                }
                if(null != data.getSumNum()){
                    allSumNum = allSumNum.add(data.getSumNum()) ;
                }
                if(data.getSecondCode().endsWith(SexEnum.M.name())){
                    manCountNum = data.getMainCodeCount();
                }else  if(data.getSecondCode().endsWith(SexEnum.F.name())){
                    womanCountNum = data.getMainCodeCount();
                }
            }
            model.addAttribute("womanscale",NumberUtil.mul(NumberUtil.div(womanCountNum.doubleValue(),allCountNum.doubleValue(),2),new Double("100")));
            model.addAttribute("manscale",NumberUtil.mul(NumberUtil.div(manCountNum.doubleValue(),allCountNum.doubleValue(),2),new Double("100")));
        }
        //根据生日计算年龄分布
        List<AnaImportData> datas6 =  consumersService.getImortDataByAge(consmersModel);
        Long before19 = 0l;//18岁以下
        Long before26up18 = 0l;//18岁以上26以下
        Long before36up25 = 0l;//25岁以上35以下
        Long before46up35 = 0l;//35岁以上46以下
        Long up45 = 0l;//45岁以上
        Long max = 5l;
        if(null != datas6 && datas6.size() > 0){
            Integer nowyear =  Integer.parseInt(DateUtils.format("yyyy"));
            for(AnaImportData data : datas6){
                try {
                    Integer year =  nowyear - Integer.parseInt(data.getSecondCode());
                    if(year <= 18){
                        before19 = before19+data.getMainCodeCount().longValue();
                    }else if(year >= 19 && year < 26 ){
                        before26up18 = before26up18+data.getMainCodeCount().longValue();

                    }else if(year >= 26 && year < 36 ){
                        before36up25 = before36up25+data.getMainCodeCount().longValue();

                    }else if(year >= 36 &&year < 46 ){
                        before46up35 = before46up35+data.getMainCodeCount().longValue();

                    }else{
                        up45 = up45+data.getMainCodeCount().longValue();

                    }
                } catch (Exception e) {

                }
            }
            //排序
            long ageValues[] = new long[]{before19,before26up18,before36up25,before46up35,up45};
            List<AgeCompareVo> ageCompareVoList = new ArrayList<AgeCompareVo>();
            for(int i=0;i<ageValues.length;i++){
                if(ageValues[i] > 0){
                    AgeCompareVo  ageVo = new AgeCompareVo();
                    ageVo.setAgeName(String.valueOf(i));
                    ageVo.setValue(ageValues[i]);
                    ageCompareVoList.add(ageVo);
                }
            }
            Collections.sort(ageCompareVoList, new Comparator<AgeCompareVo>() {
                public int compare(AgeCompareVo   arg0, AgeCompareVo   arg1) {
                    try {
                        if (arg0 != null && arg1 != null) {
                            return (int) ((arg1.getValue()-arg0.getValue()));
                        }
                    } catch (Exception ex) {
                    }
                    return 0;
                }
            });

            model.addAttribute("sortMaxList",ageCompareVoList);
        }
        model.addAttribute("before19", before19);
        model.addAttribute("before26up18", before26up18);
        model.addAttribute("before36up25", before36up25);
        model.addAttribute("before46up35", before46up35);
        model.addAttribute("up45", up45);
        model.addAttribute("max", max+before19+before26up18+before36up25+before46up35+up45);
        model.addAttribute("yes", consmersModel.getSelectButton());
        model.addAttribute("days",days);
        return "import/consumers";
    	
    }
    
    @RequestMapping("import/getConsmersData")
    public void getConsmersData(@ModelAttribute("consmersModel") ConsmersModel consumersModel,PrintWriter out)
    {
    	JSONObject object = new JSONObject();
    	
    	List<AnaImportData> consumersData=consumersService.getImportData(consumersModel);
    	if(consumersData.size()>0){
        	BigDecimal allSumPrice = new BigDecimal(new Double("0"));
            BigDecimal allSumNum = new BigDecimal(new Double("0"));
            JSONArray catrgory = new JSONArray();
            for(AnaImportData data : consumersData){
            	catrgory.add(data.getSecondCode());
                if(null != data.getSumPrice()){
                	allSumPrice = allSumPrice.add(data.getSumPrice()) ;
                }
                if(null != data.getSumNum()){
                    allSumNum = allSumNum.add(data.getSumNum()) ;
                }
            }
            object.put("category",catrgory);
            object.put("avgprice", String.valueOf(NumberUtil.div(allSumPrice.doubleValue(),allSumNum.doubleValue(),2)));
            object.put("success", true);
            out.print(object.toJSONString());
    	}
    	else{
			return;
    	}
    }


}
